const net = require('net');
const tcpServer = net.createServer();  // 创建 tcp server
const port = "8888";

let Sockets = {};	//连接池
let SocketID = 1;

 
// 监听 端口
tcpServer.listen(port,() => {
    console.log('tcpServer listening '+port);
});
 
// 处理客户端连接
tcpServer.on('connection',socket =>{
	//处理每一个连接，这里会开多个异步协程
    //console.log(socket.address());	//客户端地址
    Sockets[SocketID] =socket;
    SocketID++;
    DealConnect(socket)
})
 
tcpServer.on('error', err => {
    console.log('tcpServer error!',err);
})
 
tcpServer.on('close', ()=>{
    console.log('tcpServer close!');
})
 
// 处理每个客户端消息
function DealConnect(socket){
	
	//客户端IP
	let clientIp = socket.remoteAddress.slice(socket.remoteAddress.lastIndexOf(":")+1)+ ":" + socket.remotePort
	
	//客户端接收数据
    socket.on('data',function(data){
		
		//将buffer数据转为字符串
        data = data.toString();
		
        //向所有客户端广播消息
		// for(var i in Sockets){
		//    Sockets[i].write(data);
		// }
		
		//向当前客户端发送内容
        socket.write("ok");
		
        console.log('收到%s发来的数据:',clientIp,data);
    })
 
    // 客户端正常断开时执行
    socket.on('close', function () {
        console.log('%s断开连接!',clientIp);
    })
	
	// 客户端异常断开时执行
    socket.on("error", function (err) {
        console.log('%s客户端连接异常!',clientIp);
    });
}